package com.pingan.haofang.searchcloud.api.query.parser.dbobject.sqlnode.function;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import com.pingan.haofang.searchcloud.api.query.parser.dbobject.SqlNode;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.SqlNodeType;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.sqlnode.ColumnNode;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.util.SqlNodeUtil;

public abstract class Function extends SqlNode {

    protected List<SqlNode> params;
    protected String name;

    public Object getValue(Object...params) {
        return null;
    }

    public String getAlias() {
        if (StringUtils.isBlank(alias)) {
            return getFullName();
        }
        return alias;
    }

    @Override
    public List<ColumnNode> getColumns() {
        List<ColumnNode> result = new ArrayList<ColumnNode>();
        if (CollectionUtils.isNotEmpty(params)) {
            for (SqlNode node : params) {
                if (node.getType() == SqlNodeType.COLUMN) {
                    result.add((ColumnNode) node);
                }
            }
        }
        return result;
    }

    @Override
    public int getType() {
        return SqlNodeType.FUNCTION;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public List<SqlNode> getParams() {
        return params;
    }

    public void setParams(List<SqlNode> params) {
        this.params = params;
        validate();
    }

    public String getFullName() {
        StringBuilder sb = new StringBuilder();
        sb.append(name).append("(");
        if (params != null) {
            for (SqlNode param : params) {
                if (SqlNodeUtil.isColumn(param)) {
                    ColumnNode columnNode = (ColumnNode) param;
                    if (StringUtils.isNotBlank(columnNode.getSchema())) {
                        sb.append(columnNode.getSchema()).append(".");
                    }
                    sb.append(columnNode.getColumnName());
                } else {
                    sb.append(param.toString());
                }
            }
        }
        sb.append(")");
        return sb.toString();
    }

}
